import { login, getInfo } from "@/api/url";
import { getToken, setToken, removeToken } from "@/utils/auth";

const getDefaultState = () => {
  return {
    token: null,
    menus: [],
    usernameL:''
  };
};

const state = getDefaultState();

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_MENUS: (state, menus) => {
    state.menus = menus;
  },
  SET_NAME: (state, usernameL) => {
    state.usernameL = usernameL;
  }
};

const actions = {
  //登陆获取token
  login({ commit }, userInfo) {
    const { username, password } = userInfo;
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password })
        .then(response => {
          var tokenText = "JWT " + response.result.token;
          commit("SET_TOKEN", tokenText);
          commit("SET_NAME", response.result.name);
          sessionStorage.setItem('vue_admin_template_token', tokenText);
          setToken(tokenText);
          resolve();
        })
        .catch(error => {
          console.log(error)
          reject(error);
        });
    });
  },
  //获取路由
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo()
        .then(response => {
          commit("SET_MENUS", response.result);
          resolve(response);
        })
        .catch(error => {
          reject(error);
        });
    });
  },
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
        removeToken() 
        commit('SET_NAME',null)
        commit("SET_MENUS", []);
        resolve()
    })
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
